package org.dreamwork.jasmine2.sample.page;

import org.dreamwork.jasmine2.events.EventException;
import org.dreamwork.jasmine2.events.IClickListener;
import org.dreamwork.jasmine2.events.IValidateListener;
import org.dreamwork.jasmine2.sample.data.Product;
import org.dreamwork.jasmine2.sample.util.Const;
import org.dreamwork.jasmine2.web.IWebControl;
import org.dreamwork.jasmine2.web.controls.*;
import org.dreamwork.util.StringUtil;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by IntelliJ IDEA.
 * User: seth.yang
 * Date: 2010-10-25
 * Time: 14:45:09
 */
public class ProductPage extends Page {
    protected Product product;
    protected Product.Category[] categories = Product.Category.values ();

    protected Hidden productId;
    protected TextBox productName;
    protected DropdownList category;
    protected TextBox supplier;
    protected TextBox unit;
    protected TextBox price;
    protected TextBox store;
    protected CheckBox promote;
    protected DatePicker toDate;
    protected Button btnSave;

    @Override
    public void onPagePreload (Page page) throws EventException {
        productName.addValidateListener (emptyChecker);
        supplier.addValidateListener (emptyChecker);
        unit.addValidateListener (emptyChecker);
        price.addValidateListener (emptyChecker);
        store.addValidateListener (emptyChecker);

        price.addValidateListener (numberChecker);
        store.addValidateListener (numberChecker);

        btnSave.addClickListener (saveListener);
    }

    @Override
    public void onPageLoad (Page page) throws EventException {
//        product = findProduct ();
        if (!StringUtil.isEmpty (productId.getText ()))
            product = findProduct ();
    }

    @Override
    public void onPageLoadCompleted (Page page) throws EventException {
        try {
            dataBind ();
        } catch (Throwable throwable) {
            throwable.printStackTrace ();
        }
    }

    @SuppressWarnings ("unchecked")
    private void saveProduct (Product product) {
        product.setCategory ((Product.Category) category.getSelectedItem ());
        product.setName (productName.getText ().trim ());
        product.setPrice (Double.parseDouble (price.getText ().trim ()));
        product.setStore (Double.parseDouble (store.getText ().trim ()));
        product.setSupplier (supplier.getText ());
        product.setUnit (unit.getText ());
        product.setPromote (promote.isChecked ());
        product.setToDate (toDate.getDate ());

        HttpSession session = context.getSession ();
        List<Product> list = (List<Product>) session.getAttribute (Const.PRODUCT_LIST_DATA);
        if (list == null) {
            list = new ArrayList<Product> ();
            session.setAttribute (Const.PRODUCT_LIST_DATA, list);
        }
        list.add (product);
    }

    @SuppressWarnings ("unchecked")
    private Product findProduct () {
        HttpSession session = context.getSession ();
        List<Product> list = (List<Product>) session.getAttribute (Const.PRODUCT_LIST_DATA);
        Lock lock = new ReentrantLock ();
        if (StringUtil.isEmpty (productId.getText ())) {
            Product p = new Product ();
            try {
                lock.lock ();
                p.setId (list == null ? 1 : list.size () + 1);
            } finally {
                lock.unlock ();
            }
            return p;
        }

        int pid = Integer.parseInt (productId.getText ().trim ());
        try {
            lock.lock ();
            for (Product p : list) {
                if (p.getId () == pid) return p;
            }
        } finally {
            lock.unlock ();
        }
        return null;
    }

    private IValidateListener emptyChecker = new IValidateListener() {
        public boolean onValidate (IWebControl sender) {
            TextBox box = (TextBox) sender;
            if (isPostback () && StringUtil.isEmpty (box.getText ())) {
                box.setStyle ("border", "1px solid #f00");
                return false;
            }
            return true;
        }
    };

    private IValidateListener numberChecker = new IValidateListener() {
        public boolean onValidate (IWebControl sender) {
            if (!isPostback ()) return true;
            TextBox box = (TextBox) sender;
            try {
                Double.parseDouble (box.getText ().trim ());
                return true;
            } catch (Exception ex) {
                box.setStyle ("border", "1px solid #f00");
                return false;
            }
        }
    };

    private IClickListener saveListener = new IClickListener() {
        public void onClick (IWebControl sender) throws EventException {
            product = findProduct ();
            saveProduct (product);
            redirect ("ProductList.jasmine");
        }
    };
}